<template>
	<view class="uni-container">
		<uni-forms style="width: 100vw;" ref="form" :value="formData" validateTrigger="bind">
			<uni-forms-item name="name" label="表单名称">
				<uni-easyinput placeholder="表单名称" v-model="formData.name" trim="both" />
			</uni-forms-item>
			<uni-forms-item name="desc" label="表单简介">
				<uni-easyinput placeholder="用于存储表单介绍" v-model="formData.desc" trim="both" />
			</uni-forms-item>
			<uni-forms-item name="head_image" label="封面图">
				<uni-file-picker file-mediatype="image" return-type="object" v-model="formData.head_image" />
			</uni-forms-item>
			<uni-forms-item name="islogin" label="是否需要登录" required>
				<uni-data-checkbox v-model="formData.islogin" :localdata="formOptions.islogin_localdata" />
			</uni-forms-item>
			<uni-forms-item name="times" label="可提交次数">
				<uni-easyinput placeholder="是否需要限制单用户提交次数，必须为需要登录此字段才生效" type="number" v-model="formData.times" />
			</uni-forms-item>
			<uni-forms-item name="sort" label="排序" required>
				<uni-easyinput placeholder="默认100，排序值约小越前" type="number" v-model="formData.sort" />
			</uni-forms-item>
			<uni-forms-item name="end_date" label="到期时间">
				<uni-datetime-picker return-type="timestamp" :value="formData.end_date" />
			</uni-forms-item>

			<!-- 表单字段 -->
			<el-table :data="formItems" style="width: 80vw">
				<el-table-column prop="name" label="字段名称" width="100">
					<template slot-scope="scope">
						<el-input v-model="scope.row.name" placeholder="请输入字段名称"></el-input>
					</template>
				</el-table-column>
				<el-table-column prop="type" label="字段类型" width="120">
					<template slot-scope="scope">
						<el-select v-model="scope.row.type" placeholder="请选择">
							<el-option v-for="item in formItemType" :key="item.value" :label="item.text"
								:value="item.value"></el-option>
						</el-select>
					</template>
				</el-table-column>
				<el-table-column prop="value" label="字段值" width="180">
					<template slot-scope="scope">
						<el-input v-model="scope.row.value" placeholder="请输入字段值"></el-input>
					</template>
				</el-table-column>
				<el-table-column prop="default_value" label="默认值" width="180">
					<template slot-scope="scope">
						<el-input v-model="scope.row.default_value" placeholder="请输入默认值"></el-input>
					</template>
				</el-table-column>
				<el-table-column prop="placehold" label="提示文案" width="180">
					<template slot-scope="scope">
						<el-input v-model="scope.row.placehold" placeholder="请输入提示文案"></el-input>
					</template>
				</el-table-column>
				<el-table-column prop="isrequired" label="是否必填" width="160">
					<template slot-scope="scope">
						<el-radio-group v-model="scope.row.isrequired">
							<el-radio :label="0">选填</el-radio>
							<el-radio :label="1">必填</el-radio>
						</el-radio-group>
					</template>
				</el-table-column>
				<el-table-column prop="sort" label="排序" width="180">
					<template slot-scope="scope">
						<el-input v-model="scope.row.sort" type="number" placeholder="请输入排序号"></el-input>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="100">
					<template slot-scope="scope">
						<el-button type="text" @click="removeItem(scope.$index)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-button type="text" @click="addItem">添加一行</el-button>

			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/form.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'form';

	function getValidator(fields) {
		let reuslt = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				reuslt[key] = validator[key]
			}
		}
		return reuslt
	}

	export default {
		data() {
			return {
				formItems: [{
					name: '',
					type: 0,
					value: '',
					default_value: '',
					placehold: '',
					isrequired: 0,
					sort: 100,
					form_id: ''
				}],
				formData: {
					"name": "",
					"desc": "",
					"head_image": null,
					"islogin": 0,
					"times": 1,
					"sort": 100,
					"end_date": null
				},
				formOptions: {
					"islogin_localdata": [{
							"value": 0,
							"text": "无需登录"
						},
						{
							"value": 1,
							"text": "需要登录"
						}
					]
				},
				rules: {
					...getValidator(["name", "desc", "head_image", "islogin", "times", "sort", "end_date"])
				},
				formItemType: this.$store.state.enums.formItemType
			}
		},
		onLoad(e) {
			const id = e.id
			this.formDataId = id
			this.getDetail(id)
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			addItem() {
				this.formItems.push({
					name: '',
					type: 0,
					value: '',
					default_value: '',
					placehold: '',
					isrequired: 0,
					sort: 100
				})
			},
			/**
			 * 触发表单提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.submit().then((res) => {
					this.submitForm(res)
				}).catch((errors) => {
					uni.hideLoading()
				})
			},

			submitForm(value) {
				// 使用 clientDB 提交数据
				db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					uni.showToast({
						title: '修改成功'
					})
					
					this.submitItem()
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			submitItem(){
				var list = this.formItems.map(res => {
					res.form_id = this.formDataId
					delete res._id
					return res
				})
				db.collection('form-item').where({
					form_id: this.formDataId
				}).remove()
				db.collection('form-item').add(list).then(res => {
					uni.showToast({
						title: '编辑成功'
					})
					// this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				})
			},

			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName).doc(id).field('name,desc,head_image,islogin,times,sort,end_date').get()
					.then((res) => {
						const data = res.result.data[0]
						if (data) {
							this.formData = data
						}
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					}).finally(() => {
						uni.hideLoading()
					})
				
				db.collection('form-item').where({'form_id': id}).get()
					.then(res => {
						this.formItems = res.result.data
						console.log(res)
					})
			}
		}
	}
</script>
